package com.wangshuqi.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.wangshuqi.mybatis.spring.MyScan;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.io.InputStream;

@Configuration
@PropertySource("classpath:jdbc.properties")
//@Import(MyImportBeanDefinitionRegister.class)
@MyScan("com.wangshuqi.app.dao")
public class MybatisConfig {

    @Value("${jdbc.driverClass}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /*@Bean
    public UserMapper userMapper(SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper;
    }
*/

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//        sqlSessionFactory.getConfiguration().addMapper(UserMapper.class);
        return sqlSessionFactory;
    }

    /*
     * 配置数据库连接
     * */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
